import {ThunkAction} from 'redux-thunk'
import {RootState} from '../store'
import axios from 'axios'

export const FETCH_RECOMMEND_PRODUCTS_START = "FETCH_RECOMMEND_PRODUCTS_START" // 正在调用推荐信息API
export const FETCH_RECOMMEND_PRODUCTS_SUCCESS = "FETCH_RECOMMEND_PRODUCTS_SUCCESS" // 推荐信息API调用成功
export const FETCH_RECOMMEND_PRODUCTS_FAIL = "FETCH_RECOMMEND_PRODUCTS_FAIL" // 推荐信息API调用失败


interface FetchRecommendProductsStartAction {
  type: typeof FETCH_RECOMMEND_PRODUCTS_START
}

interface FetchRecommendProductsSuccessAction {
  type: typeof FETCH_RECOMMEND_PRODUCTS_SUCCESS,
  value: any
}

interface FetchRecommendProductsFailAction {
  type: typeof FETCH_RECOMMEND_PRODUCTS_FAIL,
  value: any
}

// 导出混合类型
export type RecommendProductAction = FetchRecommendProductsFailAction | FetchRecommendProductsSuccessAction | FetchRecommendProductsStartAction

// action创建工厂
// 请求开始
export const fetchRecommendProductsStartActionCreator = (): FetchRecommendProductsStartAction => {
  return {
    type: FETCH_RECOMMEND_PRODUCTS_START
  }
}

// 请求成功
export const fetchRecommendProductsSuccessActionCreator = (data): FetchRecommendProductsSuccessAction => {
  return {
    type: FETCH_RECOMMEND_PRODUCTS_SUCCESS,
    value: data
  }
}

// 请求失败
export const fetchRecommendProductsFailActionCreator = (data): FetchRecommendProductsFailAction => {
  return {
    type: FETCH_RECOMMEND_PRODUCTS_FAIL,
    value: data
  }
}


// thunk可以返回一个函数,而不一定是js(action)对象
// 在一个thunk中可以完成一些列连续的action操作
// 并且在thunk中可以处理异步逻辑
export const giveMeDataActionCreator = () : ThunkAction<void, RootState, unknown, RecommendProductAction> =>  async (dispatch, getState) => {
  dispatch(fetchRecommendProductsStartActionCreator())
    try {
      const {data} = await axios.get('http://asdasdasdasdasdasd')
      dispatch(fetchRecommendProductsSuccessActionCreator(data))
    } catch (error) {
      dispatch(fetchRecommendProductsFailActionCreator(error))
    }
}